const express = require('express');
const {executeQuery} = require('../config/db_config')
const {
    escape
} = require('mysql')
const router = express.Router();
const emailService = require('../utils/emailService');

// 发送绑定邮箱验证码
router.post('/code/bind', async (req, res) => {
    try {
        const {
            email
        } = req.body;
        await emailService.sendVerificationCode(email, 'bind');
        res.json({
            code: 200,
            message: '验证码已发送'
        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            message: error.message
        });
    }
});

// 发送换绑邮箱验证码
router.post('/code/change', async (req, res) => {
    try {
        const {
            email
        } = req.body;
        await emailService.sendVerificationCode(email, 'change');
        res.json({
            code: 200,
            message: '验证码已发送'
        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            message: error.message
        });
    }
});

// 发送重置密码验证码
router.post('/code/resetPassword', async (req, res) => {
    try {
        console.log(req.body)
        const {
            username
        } = req.body;
        const sql = `select * from user where username=${escape(username)}`
        const user = await executeQuery(sql)
        console.log(user)
        if (user.length == 0) {
            res.status(400).json({
                code: 400,
                message: '用户不存在'
            });
        }
        if(!user[0].email) {
            res.status(400).json({
                code: 400,
                message: '用户未绑定邮箱,请联系管理员处理'
            });
        }

        await emailService.sendVerificationCode(user[0].email, 'reset-password');
        res.json({
            code: 200,
            message: '验证码已发送',
            data: {
                email: user[0].email
            }
        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            message: error.message
        });
    }
});

module.exports = router;